<?php

namespace app\admin\controller;

use app\admin\service\ConfigService;
use app\admin\service\ConsultantExportService;
use app\admin\service\UserExportService;
use app\admin\service\UserImportService;
use app\admin\service\userSeniorExportService;
use app\admin\service\UserService;
use app\BaseController;
use app\model\archives_model\UserArchiveCustomTemplateModel;
use app\model\archives_model\UserArchiveModel;
use app\model\archives_model\UserArchiveTemplateModel;
use app\model\archives_model\UserArchiveTypeModel;
use app\model\ConfigModel;
use app\model\ConsultOfflineModel;
use app\model\ConsultOfflineTaskModel;
use app\model\ConsultOnlineMessageModel;
use app\model\ConsultOnlineModel;
use app\model\ConsultTimeModel;
use app\model\DepartmentAdminModel;
use app\model\DepartmentModel;
use app\model\RoleModel;
use app\model\TagModel;
use app\model\UnitModel;
use app\model\UserModel;
use app\model\UserTagModel;
use app\socket\Server;
use PhpOffice\PhpWord\TemplateProcessor;
use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use app\model\not_del\UserModel as NotDelUserModel;
use think\swoole\Websocket;

class User extends BaseController
{
    protected $mode;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->mode = new UserModel();
    }

    /**
     * 标签选择器
     * @return false|string
     */
    public function tagSelector(): bool|string
    {
        try {
            $TagModel = new TagModel();
            $data = $TagModel->field('id,name,icon')->select();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 角色选择器
     * @return false|string
     */
    public function roleSelector(): bool|string
    {
        try {
            $RoleModel = new RoleModel();
            $data = $RoleModel->field('id,name,mode')
                ->where('unit_id', '=', $this->userData['unit_id'])->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 禁止登录
     * @return false|string
     */
    public function prohibitLogin(): bool|string
    {
        $id = $this->request->post('id');
        $status = $this->request->post('status');
        try {
            if (is_array($id)) {
                $this->mode->where('id', 'in', $id)->update([
                    'status' => $status
                ]);
            } else {
                $this->mode->where('id', '=', $id)->update([
                    'status' => $status
                ]);
            }
            return success([], '更新成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 获取账号申述信息
     * @return bool|string
     */
    public function getAppealInfo(): bool|string
    {
        $id = $this->request->post('id');
        try {
            $UserModel = new UserModel();
            $field = ['id,username,name,sex,status,appeal_reason,department_id'];
            $data = $UserModel->where('id', $id)->field($field)->find();
            $data = $data ? $data->toArray() : ['data' => []];
            if (count($data) > 0) {
                $UserService = new UserService($this->app);
                $getDepartmentAffiliationAll2 = $UserService->getDepartmentAffiliationAll2($this->userData['unit_id'], [$data['department_id']]);
                $data['class_name'] = $getDepartmentAffiliationAll2['department_data'][$data['department_id']]['all_name'];
            }
            return success($data, '操作成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 重置密码
     * @return false|string
     */
    public function resetPassword(): bool|string
    {
        $id = $this->request->post('id');
        try {
            $password = encrypt_password(env('USER_PASSWORD', 123456));
            if (is_array($id)) {
                $this->mode->where('id', 'in', $id)->update([
                    'password' => $password,
                    'status' => 1
                ]);
            } else {
                $this->mode->where('id', '=', $id)->update([
                    'password' => $password,
                    'status' => 1
                ]);
            }
            return success([], '重置成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 添加账号
     * @return false|string
     */
    public function add(): bool|string
    {
        $param = $this->request->param();
        try {
            $this->validate($param, [
                'username|账号'  =>  'require|length:8,18|alphaNum',
                'password|密码'  =>  'require|length:8,18',
                'name|姓名' =>  'require',
                'sex|性别' =>  'require',
                'role_id|角色' =>  'require',
            ],[
                'username.require' => '账号不能为空',
                'username.length'     => '账号长度不符合要求，8-18位字符',
                'username.alphaNum'     => '账号格式不符合要求，字母或数字',
                'password.require'        => '密码不能为空',
                'password.length'        => '密码长度不符合要求，8-18位字符',
            ]);
            $uid = $this->mode->where('username', '=', $param['username'])->value('id');
            if ($uid) throw new \Exception('账号已存在！');
            //验证当前是学院制，还是非学院制
            $ConfigService = new ConfigService($this->app);
            $config = $ConfigService->getConfig($this->userData['unit_id'], 'department_management');
            if ($config['type'] == 2 && !empty($param['department_id'])) {
                //如果是学院制，选择的部门必须大于等于第三层级（班级）
                $department = new DepartmentModel();
                $level = $department->where('id', $param['department_id'])->value('level');
                if ($level <= 2) throw new \Exception('学院制新增用户必须选择第三级部门或者以下等级的部门！');
            }
            $RoleModel = new RoleModel();
            $RoleInfo = $RoleModel->where('id', '=', $param['role_id'])->find();
            $param['role_mode'] = $RoleInfo['mode'];
            $param['company_id'] = $this->userData['company_id'];
            $param['areas_id'] = $this->userData['areas_id'];
            $param['unit_id'] = $this->userData['unit_id'];
            $param['level'] = $this->userData['level'];
            $param['province_id'] = $this->userData['province_id'];
            $param['city_id'] = $this->userData['city_id'];
            $param['area_id'] = $this->userData['area_id'];
            $param['province_name'] = $this->userData['province_name'];
            $param['city_name'] = $this->userData['city_name'];
            $param['area_name'] = $this->userData['area_name'];
            $param['type'] = 4;
            $param['time'] = time();
            $param['password'] = encrypt_password($param['password']);
            if ($RoleInfo['mode'] < 3) $param['type'] = 3;
            if (empty($param['avatar'])) {
                $UserService = new UserService($this->app);
                switch ($RoleInfo['mode']) {
                    case 1:
                        $param['avatar'] = $UserService->getDefaultAvatar('admin');
                        break;
                    case 2:
                        if ($param['sex'] == 1) {
                            $param['avatar'] = $UserService->getDefaultAvatar('male_counselor');
                        } else {
                            $param['avatar'] = $UserService->getDefaultAvatar('female_counselor');
                        }
                        break;
                    default:
                        if ($param['sex'] == 1) {
                            $param['avatar'] = $UserService->getDefaultAvatar('male');
                        } else {
                            $param['avatar'] = $UserService->getDefaultAvatar('female');
                        }

                }
            }
            if (!empty($param['tag'])) {
                $tag = $param['tag'];
                unset($param['tag']);
                $uid = $this->mode->insertGetId($param);
                $tagData = [];
                foreach ($tag as $v) {
                    $tagData[] = [
                        'uid' => $uid,
                        'tag_id' => $v,
                        'time' => time()
                    ];
                }
                if (count($tagData) > 0) {
                    $UserTagModel = new UserTagModel();
                    $UserTagModel->insertAll($tagData);
                }
            } else {
                $this->mode->insert($param);
            }
            return success([], '添加成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 编辑账号
     * @return false|string
     */
    public function update(): bool|string
    {
        $this->mode->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|integer',
            ]);
            $info = $this->mode->find($param['id']);
            if (!$info) return error('参数错误！');
            if (!empty($param['password'])) {
                if (!validatePassword($param['password'])) throw new \Exception('密码不满足8-18位字符！');
                $param['password'] = encrypt_password($param['password']);
            }
            if (!empty($param['parent_password'])) {
                if (!validatePassword($param['parent_password'])) throw new \Exception('家长密码不满足8-18位字符！');
                $param['parent_password'] = encrypt_password($param['parent_password']);
            }
            if (!empty($param['tag'])) {
                $tag = $param['tag'];
                unset($param['tag']);
                $tagData = [];
                foreach ($tag as $v) {
                    $tagData[] = [
                        'uid' => $info->id,
                        'tag_id' => $v,
                        'time' => time()
                    ];
                }
                if (count($tagData) > 0) {
                    $UserTagModel = new UserTagModel();
                    $UserTagModel->where('uid', '=', $info->id)->update([
                        'is_del' => 1,
                        'del_time' => time()
                    ]);
                    $UserTagModel->insertAll($tagData);
                }
            }
            $param = array_filter($param,'strlen');
            $info->save($param);
            $this->mode->commit();
            return success([], '更新成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 删除账号
     * @return false|string
     */
    public function del(): bool|string
    {
        $this->mode->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $DepartmentAdminModel = new DepartmentAdminModel();
            $ConsultTimeModel = new ConsultTimeModel();
            $UnitModel = new UnitModel();
            if (is_array($param['id'])) {
                $this->mode->where('id', 'in', $param['id'])->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
                $DepartmentAdminModel->where('uid', 'in', $param['id'])->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
                $ConsultTimeModel->where('consult_id', 'in', $param['id'])->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
                $UnitModel->where('id','=',$this->userData['unit_id'])->dec('add_user_num',count($param['id']))->save();
            } else {
                $this->mode->where('id', '=', $param['id'])->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
                $DepartmentAdminModel->where('uid', '=', $param['id'])->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
                $ConsultTimeModel->where('consult_id', '=', $param['id'])->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
                $UnitModel->where('id','=',$this->userData['unit_id'])->dec('add_user_num')->save();
            }
            $this->mode->commit();
            return success([], '删除成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 普通用户列表
     * @return false|string
     */
    public function userList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $UserService = new UserService($this->app);
            $DepartmentAdminModel = new DepartmentAdminModel();
            if (!empty($param['role_id'])) {
                $where[] = ['role_id', '=', $param['role_id']];
            }
            if (!empty($param['status'])) {
                $where[] = ['status', '=', $param['status']];
            }
            if (!empty($param['name'])) {
                $where[] = ['name|username', 'like', '%' . $param['name'] . '%'];
            }
            if (isset($param['sex']) && strlen($param['sex']) > 0) {
                $where[] = ['sex', '=', $param['sex']];
            }
            if (isset($param['student_status']) && strlen($param['student_status']) > 0) {
                $where[] = ['student_status', '=', $param['student_status']];
            }
            if (isset($param['department_id']) && strlen($param['department_id']) > 0) {
                $department_id = $UserService->getDepartmentAllLowerLevelIds($this->userData['unit_id'],[$param['department_id']]);
                $where[] = ['department_id', 'in', $department_id];
            }
            if (!empty($param['id'])){
                $where[] = ['id', 'in', $param['id']];
            }
            if ($this->userData['role_id'] > 0){
                $department_ids = $DepartmentAdminModel->where('uid', '=', $this->userData['id'])->column('department_id');
                if (!empty($department_ids)) {
                    $where[] = ['department_id', 'in', $department_ids];
                } else {
                    $where[] = ['department_id', '=', '-1'];
                }
            }else{
                if (!empty($param['department_admin_id'])) {
                    $department_ids = $DepartmentAdminModel->where('uid', '=', $param['department_admin_id'])->column('department_id');
                    if (!empty($department_ids)) {
                        $where[] = ['department_id', 'in', $department_ids];
                    } else {
                        $where[] = ['department_id', '=', '-1'];
                    }
                }
            }
            $where[] = ['role_mode', '=', 3];
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $query = $this->mode->where($where);
            $data = $query->paginate($param['pageSize'])->toArray();
            if (!empty($data['data'])) {
                $DepartmentAffiliationAll = $UserService->getDepartmentAffiliationAll($this->userData['unit_id']);
                $department_ids = array_column($data['data'], 'department_id');
                $DepartmentAdminAll = $UserService->getDepartmentAdminAll($department_ids);
                foreach ($data['data'] as &$item) {
                    //部门归属
                    $item['ascription_name'] = $DepartmentAffiliationAll[$item['department_id']]['ascription_name'] ?? '';
                    //所在部门
                    $item['department_name'] = $DepartmentAffiliationAll[$item['department_id']]['all_name'] ?? '';
                    //部门number（班级编号）
                    $item['department_number'] = $DepartmentAffiliationAll[$item['department_id']]['number'] ?? '';
                    //部门管理员
                    $item['department_admin'] = $DepartmentAdminAll[$item['department_id']]['user_name'] ?? '';
                }
            }
            $ConfigModel = new ConfigModel();
            $data['config'] = json_decode($ConfigModel->where([
                'unit_id' => $this->userData['unit_id'],
                'key' => 'department_management'
            ])->value('value')??'',true);
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 高级筛选-导出【普通用户】
     * @return bool|string
     */
    public function userSeniorExport(): bool|string
    {
        try {
            $param = $this->request->param();
            $param['role_mode'] = $this->userData['role_mode'];
            $param['unit_id'] = $this->userData['unit_id'];
            $param['user_id'] = $this->userData['id'];
            $userSeniorExportService = new userSeniorExportService($this->app);
            $ret = $userSeniorExportService->userSeniorExport($param);
            if (!$ret) throw new \Exception($userSeniorExportService->getMessage());
            return success($userSeniorExportService->getResult());
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 高级筛选-导出【普通用户id集合】
     * @return bool|string
     */
    public function getUserIdExport(): bool|string
    {
        try {
            $param = $this->request->param();
            $param['role_mode'] = $this->userData['role_mode'];
            $param['unit_id'] = $this->userData['unit_id'];
            $param['user_id'] = $this->userData['id'];
            $userSeniorExportService = new userSeniorExportService($this->app);
            $ret = $userSeniorExportService->getUserIdExport($param);
            if (!$ret) throw new \Exception($userSeniorExportService->getMessage());
            return success($userSeniorExportService->getResult());
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 咨询师列表
     * @return false|string
     */
    public function consultantList(): bool|string
    {
        try {
            $ConsultTimeModel = new ConsultTimeModel();
            $DepartmentModel = new DepartmentModel();
            $param = $this->request->param();
            $where = [];
            if (!empty($param['role_id'])) {
                $where[] = ['role_id', '=', $param['role_id']];
            }
            if (!empty($param['name'])) {
                $where[] = ['name|username', 'like', '%' . $param['name'] . '%'];
            }
            if (isset($param['is_scheduling']) && strlen($param['is_scheduling']) > 0) {
                $where[] = ['is_scheduling', '=', $param['is_scheduling']];
            }
            if (isset($param['sex']) && strlen($param['sex']) > 0) {
                $where[] = ['sex', '=', $param['sex']];
            }
            if (isset($param['tag_id']) && strlen($param['tag_id']) > 0) {
                $UserTagModel = new UserTagModel();
                $uids = $UserTagModel->where('tag_id', '=', $param['tag_id'])->column('uid');
                if (count($uids) > 0) {
                    $where[] = ['id', 'in', $uids];
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            if (!empty($param['id'])){
                $where[] = ['id', 'in', $param['id']];
            }
            //搜索有无排班
            if (isset($param['scheduling_day']) && strlen($param['scheduling_day']) > 0) {
                $consult_id = $ConsultTimeModel->where([
                    ['unit_id','=',$this->userData['unit_id']],
                    ['start_time', '>', time()]
                ])->column('consult_id');
                if ($param['scheduling_day'] == 0) {
                    //无排班
                    if (count($consult_id) > 0){
                        $where[] = ['id','not in', $consult_id];
                    }
                } else {
                    //有排班
                    if (count($consult_id) > 0){
                        $where[] = ['id','in', $consult_id];
                    }
                }
            }
            //搜索服务对象类型
            if (isset($param['scheduling_object']) && strlen($param['scheduling_object']) > 0) {
                if ($param['scheduling_object'] == 0) {
                    //服务所有部门
                    $consult_id = $ConsultTimeModel->where([
                        ['unit_id','=',$this->userData['unit_id']],
                        ['start_time', '>', time()],
                        ['department_id','=',0]
                    ])->column('consult_id');
                } else {
                    //服务部分部门
                    $consult_id = $ConsultTimeModel->where([
                        ['unit_id','=',$this->userData['unit_id']],
                        ['start_time', '>', time()],
                        ['department_id','>',0]
                    ])->column('consult_id');
                }
                if (count($consult_id) > 0){
                    $where[] = ['id','in', $consult_id];
                }
            }
            $where[] = ['role_mode', '=', 2];
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $query = $this->mode->where($where);
            $data = $query->with([
                'unitName',
                'userTag' => function ($queue) {
                    $queue->with(['tag']);
                },
                'ConsultTime'
            ])->paginate($param['pageSize'])->toArray();
            if (count($data) > 0) {
                foreach ($data['data'] as &$item) {
                    //服务对象
                    $DepartmentIds = array_column($item['ConsultTime'], 'department_id');
                    if (count($DepartmentIds) > 0) {
                        if (in_array(0,$DepartmentIds)) {
                            $ServerObject = '服务所有部门';
                            //排班服务类型
                            $ServerType = '所有部门';
                        } else {
                            $ServerObject = '服务指定部门';
                            //排班服务类型
                            $DepartmentNames = $DepartmentModel->where('id','in',$DepartmentIds)->column('name');
                            $ServerType = implode('、',$DepartmentNames);
                        }
                    }else{
                        $ServerObject = '--';
                        $ServerType = '--';
                    }
                    //排班情况
                    $ConsultDate = array_column($item['ConsultTime'],'date');
                    $ConsultDate = array_unique($ConsultDate);
                    $day = count($ConsultDate);
                    $item['scheduling_day'] = $day ? '已排班' : '未排班'; //排班情况
                    $item['scheduling_day_num'] = $day ? $day . '天' : '--'; //排班情况
                    $item['service_object'] = $ServerObject;//服务对象 [指定部门或者所有部门]
                    $item['service_type'] = $ServerType;//服务类型
                }
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 高级筛选-导出【咨询师】
     * @return bool|string
     */
    public function consultantSeniorExport(): bool|string
    {
        try {
            $param = $this->request->param();
            $param['role_mode'] = $this->userData['role_mode'];
            $param['unit_id'] = $this->userData['unit_id'];
            $param['user_id'] = $this->userData['id'];
            $consultantSeniorExportService = new ConsultantExportService($this->app);
            $ret = $consultantSeniorExportService->consultantSeniorExport($param);
            if (!$ret) throw new \Exception($consultantSeniorExportService->getMessage());
            return success($consultantSeniorExportService->getResult());
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 高级筛选-导出【获取咨询师ID】
     * @return bool|string
     */
    public function getConsultantIdExport(): bool|string
    {
        try {
            $param = $this->request->param();
            if (empty($param['is_scheduling']) && empty($param['start_time']) && empty($param['end_time']) && empty($param['sex']) && empty($param['department_id']) && empty($param['tags']) && empty($param['statisticsItems'])){
                throw new \Exception('请选择筛选条件！');
            }
            $param['role_mode'] = $this->userData['role_mode'];
            $param['unit_id'] = $this->userData['unit_id'];
            $param['user_id'] = $this->userData['id'];
            $consultantSeniorExportService = new ConsultantExportService($this->app);
            $ret = $consultantSeniorExportService->getConsultantIdExport($param);
            if (!$ret) throw new \Exception($consultantSeniorExportService->getMessage());
//            foreach ($consultantSeniorExportService->getResult() as $key => $item) {
//                $oneModel = new ConsultantService($this->app);
//                $one = $oneModel->getQuestionType($item, $param['unit_id']);
//                $two = $oneModel->getOneMonthPeopleNumber($item, $param['unit_id']);
//                $three = $oneModel->getOneReceptionCapacity($item, $param['unit_id']);
//                $list[$key]['consultant_id'] = $item;
//                $list[$key]['info']['one'] = $one;
//                $list[$key]['info']['two'] = $two;
//                $list[$key]['info']['three'] = $three;
//            }
            return success($ret);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 管理员列表
     * @return false|string
     */
    public function adminList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['role_id'])) {
                $where[] = ['role_id', '=', $param['role_id']];
            }
            if (!empty($param['name'])) {
                $where[] = ['name|username', 'like', '%' . $param['name'] . '%'];
            }
            if (isset($param['sex']) && strlen($param['sex']) > 0) {
                $where[] = ['sex', '=', $param['sex']];
            }
            if (!empty($param['department_id'])) {
                $DepartmentAdminModel = new DepartmentAdminModel();
                $uids = $DepartmentAdminModel->where('department_id', '=', $param['department_id'])->distinct(true)->column('uid');
                if (count($uids) > 0) {
                    $where[] = ['id', 'in', $uids];
                } else {
                    $where[] = ['id', '=', '-1'];
                }
            }
            if (isset($param['department_id']) && $param['department_id'] == 0) {
                $DepartmentModel = new DepartmentModel();
                $department_id = $DepartmentModel->where('unit_id', '=', $this->userData['unit_id'])->column('id');
                $DepartmentAdminModel = new DepartmentAdminModel();
                $uid = $DepartmentAdminModel->where('department_id', 'in', $department_id)->distinct(true)->column('uid');
                $where[] = ['id', 'not in', $uid];
            }
            if (!empty($param['level'])) {
                $DepartmentModel = new DepartmentModel();
                $uids = $DepartmentModel->where('level', '=', $param['level'])
                    ->with(['departmentAdmins' => function ($query) {
                        $query->field('id,uid,department_id');
                    }])
                    ->field('id')->select();
                if (count($uids) > 0) {
                    $ids = [];
                    foreach ($uids as $item) {
                        if (!empty($item['departmentAdmins'])) {
                            foreach ($item['departmentAdmins'] as $v) {
                                $ids[] = $v['uid'];
                            }
                        }
                    }
                    $where[] = ['id', 'in', array_unique($ids)];
                } else {
                    $where[] = ['id', '=', '-1'];
                }
            }
            $where[] = ['role_mode', '=', 1];
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $query = $this->mode->where($where);
            $data = $query->with([
                'unitName',
                'DepartmentAdmins' => function ($queue) {
                    $queue->with(['Department']);
                }
            ])->paginate($param['pageSize'])->toArray();
            $UserService = new UserService($this->app);
            $DepartmentAll = $UserService->getDepartmentAffiliationAll($this->userData['unit_id']);
            foreach ($data['data'] as &$item) {
                if (empty($item['DepartmentAdmins'])) {
                    $item['level_name'] = '0级管理员';
                } else {
                    $department_level = min(array_column($item['DepartmentAdmins'], 'department_level'));
                    $item['level_name'] = $department_level . '级管理员';
                }
                $item['admin_department'] = '';
                if (count($item['DepartmentAdmins'])){
                    $field = [];
                    foreach ($item['DepartmentAdmins'] as $key => $row) {
                        $field[$key]  = $row['department_id'];
                    }
                    array_multisort($field, SORT_ASC, $item['DepartmentAdmins']); // 假设按’field’字段升序排序
                    foreach ($item['DepartmentAdmins'] as $v) {
                        if (empty($item['admin_department'])) {
                            $item['admin_department'] = $DepartmentAll[$v['department_id']]['all_name'] ?? '';
                        } else {
                            $item['admin_department'] .= '、' . $DepartmentAll[$v['department_id']]['all_name'] ?? '';
                        }
                    }
                }

            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 下载模板
     * @return false|string
     */
    public function downloadTemplate(): bool|string
    {
        try {
            $type = $this->request->param('type');
            if ($type == 1) {
                $ConfigService = new ConfigService($this->app);
                $config = $ConfigService->getConfig($this->userData['unit_id'], 'department_management');
                if ($config['type'] == 1) {
                    $url = '/template/user.xlsx';
                } else {
                    $url = '/template/school_user.xlsx';
                }
            } elseif ($type == 2) {
                $url = '/template/consultant.xlsx';
            } elseif ($type == 3) {
                $url = '/template/admin.xlsx';
            } else {
                return error('参数错误！');
            }
            return success(['url' => $url]);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 导入用户
     * @return false|string
     */
    public function userImport(): bool|string
    {
        $this->mode->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'role_id|角色' => 'require',
                'file|文件地址' => 'require'
            ]);
            $RoleModel = new RoleModel();
            $RoleInfo = $RoleModel->find($param['role_id']);
            $type = 3;
            if ($RoleInfo['mode'] == 3) {
                $type = 4;
            }
            $UserImportService = new UserImportService($this->app);
            if (!$UserImportService->import($param['file'], [
                'company_id' => $this->userData['company_id'],
                'areas_id' => $this->userData['areas_id'],
                'unit_id' => $this->userData['unit_id'],
                'role_id' => $RoleInfo['id'],
                'role_mode' => $RoleInfo['mode'],
                'type' => $type,
                'province_id' => $this->userData['province_id'],
                'city_id' => $this->userData['city_id'],
                'area_id' => $this->userData['area_id'],
                'province_name' => $this->userData['province_name'],
                'city_name' => $this->userData['city_name'],
                'area_name' => $this->userData['area_name'],
            ])) throw new \Exception($UserImportService->message);
            $this->mode->commit();
            return success([], '导入成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            // 上传单文件
            $upload = new \app\common\Upload();
            // 设置上传类型和文件大小
            $upload = $upload->defaultConfig();
            $ext = '.txt';
            $url = $upload->upload($e->getMessage(),'binary',$ext);
            return error('导入失败！',$e->getCode(),[
                'url' => $url
            ]);
        }
    }

    /**
     * 获取档案种类
     * @return bool|string
     */
    public function getArchivesCategory(): bool|string
    {
        $list = UserArchiveTypeModel::query()->select();
        return success($list);
    }

    /**
     * 政治面貌选择器
     * @return false|string
     */
    public function politicalOutlookSelector(): bool|string
    {
        $data = new UserService($this->app);
        $data = $data->getPoliticalOutlookSelector();
        return success($data);
    }

    /**
     * 婚姻状况选择器
     * @return false|string
     */
    public function maritalStatusSelector(): bool|string
    {
        $data = new UserService($this->app);
        $data = $data->getMaritalStatusSelector();
        return success($data);
    }

    /**
     * 学籍状态选择器
     * @return false|string
     */
    public function studentStatusSelector(): bool|string
    {
        $data = new UserService($this->app);
        $data = $data->getStudentStatusSelector();
        return success($data);
    }

    /**
     * 民族选择器
     * @return false|string
     */
    public function nationSelector(): bool|string
    {
        $data = new UserService($this->app);
        $data = $data->getNationSelector();
        return success($data);
    }

    /**
     * 详细资料-获取基础信息
     * @return bool|string
     */
    public function getBasis(): bool|string
    {
        $param = $this->request->param();
        $key = ['id'];
        foreach ($key as $item) {
            if (!check_array_key($item, $param)) {
                return error('缺少参数！');
            }
        }
        try {
            $field = 'id,name,sex,age,unit_id,department_id,user_number,student_status,id_card,birthday,phone,native_place,political_outlook,
            nation,marital_status,career,interest,address,unit_id,update_time,time';
            $UserModel = new NotDelUserModel();
            $list = $UserModel->where('id', $param['id'])
                ->with(['departmentNameMode' => function ($query) {
                    $query->with(['departmentLevel']);
                }, 'unitName'])
                ->field($field)->find();
            if (!empty($list)) {
                if (!empty($list['level_rules'])) {
                    $list['level_rules'] = json_decode($list['level_rules']);
                    if ($list['level_rules']) {
                        $list['level_rules_name'] = $list['level_rules'][$list['department_stage']];
                    }
                }
                //获取部门名称
                $UserService = new UserService($this->app);
                $DepartmentAffiliationAll = $UserService->getNotDelDepartmentAffiliationAll2($list['unit_id'],[$list['department_id']]);
                $list['department_name'] = $DepartmentAffiliationAll['department_data'][$list['department_id']]['all_name'] ?? '';
                $list['marital_status'] = empty($list['marital_status']) ? 0 : $list['marital_status'];
                $list['political_outlook'] = empty($list['political_outlook']) ? 0 : $list['political_outlook'];
                $list['student_status'] = empty($list['student_status']) ? 0 : $list['student_status'];
                if ($list['update_time'] == 0) $list['update_time'] = $list['time'];
            }
            return success($list, '操作成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**add
     * 更新详细资料-修改基础资料
     * @return bool|string
     */
    public function updateBasis(): bool|string
    {
//        $key = ['id', 'age', 'sex', 'name', 'user_number', 'id_card', 'birthday', 'phone', 'native_place', 'political_outlook',
//            'nation', 'marital_status', 'career', 'interest', 'address', 'student_status', 'department_id'];
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
//            foreach ($key as $item) {
//                if (check_array_key($item, $param)) {
//                    switch ($item) {
//                        case 'id_card':
//                            //验证身份证长度与不能重复
//                            if (!isIdCard($param['id_card'])) throw new \Exception('身份证号格式错误！');
//                            $is = $this->mode->where([['id_card', '=', $param['id_card']], ['id', '<>', $param['id']]])->value('id');
//                            if ($is) throw new \Exception('身份证号重复！');
//                            break;
//                        case 'department_id':
//                            //验证当前是学院制，还是非学院制
//                            $ConfigService = new ConfigService($this->app);
//                            $config = $ConfigService->getConfig($this->userData['unit_id'], 'department_management');
//                            if ($config['type'] == 2) {
//                                //如果是学院制，选择的部门必须大于等于第三层级（班级）
//                                $department = new DepartmentModel();
//                                $level = $department->where('id', $param['department_id'])->value('level');
//                                if ($level <= 2) throw new \Exception('学院制新增用户必须选择第三级部门或者以下等级的部门！');
//                            }
//                            break;
//                    }
//
//                    $update[$item] = $param[$item];
//                } else {
//                    if ($item == 'id') {
//                        throw new \Exception('缺少参数ID！');
//                    }
//                }
//            }
            //验证身份证长度与不能重复
            if (!empty($param['id_card'])){
                if (!isIdCard($param['id_card'])) throw new \Exception('身份证号格式错误！');
                $is = $this->mode->where([['id_card', '=', $param['id_card']], ['id', '<>', $param['id']]])->value('id');
                if ($is) throw new \Exception('身份证号重复！');
            }
            if (!empty($param['department_id'])){
                //验证当前是学院制，还是非学院制
                $ConfigService = new ConfigService($this->app);
                $config = $ConfigService->getConfig($this->userData['unit_id'], 'department_management');
                if ($config['type'] == 2) {
                    //如果是学院制，选择的部门必须大于等于第三层级（班级）
                    $department = new DepartmentModel();
                    $level = $department->where('id', $param['department_id'])->value('level');
                    if ($level <= 2) throw new \Exception('学院制新增用户必须选择第三级部门或者以下等级的部门！');
                }
            }
            $update = $param;
            $userModel = new UserModel();
            //如果此用户已经毕业。学籍状态已毕业【只能更新部门字段。其他都不能操作】
            $info = $userModel->where('id', $param['id'])->value('student_status');
            if ($info == 2 && (count($update) > 2 || !isset($update['student_status']))) throw new \Exception('此用户已毕业，只能编辑部门，其他都不能操作！');
            if (!isset($update)) throw new \Exception('暂无修改信息！');
            $update['archive_update_time'] = time();
            $update['update_time'] = time();
            $update['is_normal'] = 1;
            $info = $userModel->where('id', '=', $param['id'])->update($update);
            return success($info, '更新成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取用户档案-获取问题列表信息
     * @return bool|string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getTemplateList(): bool|string
    {
        $data = $this->request->param();
        $whereArr = [];
        if (check_array_key('id', $data)) {
            $whereArr[] = ['id', '=', $data['id']];
        }
        //通用模板
        $model = UserArchiveTypeModel::query()
            ->where($whereArr)
            ->with(['templates' => function (Query $query) {
                $query->with(['templateOptions'])->where('is_can_custom', '=', 0)->append(['is_custom']);
            }])
            ->select();
        $list = $model->toArray();
        foreach ($list as $key => $value) {
            $temp = [];
            $templateList = [];
            $templateList = set_array_key($value['templates']);
            array_to_tree($templateList, $temp);
            $temp = array_values($temp);
            $list[$key]['templates'] = $temp;
        }
        return success($list);
    }

    /**
     * 获取用户档案得结果
     * @return bool|string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getUserArchive(): bool|string
    {
        $param = $this->request->param();
        $key = ['user_id', 'type_id'];
        foreach ($key as $item) {
            if (!check_array_key($item, $param)) {
                return error('缺少参数!');
            }
        }
        if (!isset($param['pageSize'])) {
            $param['page'] = 1;
            $param['pageSize'] = 1;
        }
        $where = [
            ['user_id', '=', $param['user_id']],
            ['type_id', '=', $param['type_id']],
        ];
        if (isset($param['result_id'])) {
            //只有线下。线上查结果需要
            $return = UserArchiveModel::query()->where('id', $param['result_id'])->find();
        } else {
            if (!isset($param['type'])) {
                //用户列表这边的数据
                $return = UserArchiveModel::query()->where($where)->with(['getUserInfo'])->order('time desc')->limit(1)->select();
            } else {
                //档案库的用的数据
                if (check_array_key('isAbandon', $param)) {
                    //废弃档案
                    $where[] = ['is_repeal', '=', 0];
                } else {
                    //正常档案
                    $where[] = ['is_repeal', '=', 0];
                }
                $return = UserArchiveModel::query()->where($where)->order('time desc')->paginate($param['pageSize']);
            }
        }
        return success($return);
    }

    /**
     * 保存记录【整个模块一起修改】
     * @param Websocket $websocket
     * @return bool|string
     */
    public function editUserArchive(Websocket $websocket): bool|string
    {
        $this->mode->startTrans();
        try {
            //TODO::验证json数据里面的每个数据，暂时不做
            $param = $this->request->param();
            $this->validate($param,[
                'user_id|用户ID' => 'require',
                'content|内容' => 'require',
                'type_id|类型ID' => 'require',
                'source|渠道' => 'require',
            ]);
            $update['update_uid'] = $this->userData['id'];
            $update['type_id'] = $param['type_id'];
            $update['unit_id'] = $this->mode->where('id', $param['user_id'])->value('unit_id');
            $update['user_id'] = $param['user_id'];
            $update['content'] = $param['content'];
            $update['source'] = $param['source'];
            $userArchiveModel = new UserArchiveModel();
            $where = [
                ['unit_id', '=', $update['unit_id']],
                ['user_id', '=', $param['user_id']],
                ['type_id', '=', $param['type_id']],
                ['is_repeal', '=', 0],
            ];
            $ret = $userArchiveModel->query()->where($where)->find();

            //编辑
            $update['update_time'] = time();
            switch ($param['type_id']) {
                case 1:
                    if (!check_array_key('message_id', $param)) {
                        throw new \Exception('缺少参数！');
                    }
                    $update['source_id'] = $param['message_id'];
                    //只有新增，保留每一次的保存记录
                    $update['time'] = time();
                    $id = $userArchiveModel->insertGetId($update);
                    switch ($param['source']) {
                        case 1:
                        case 5:
                            //不处理
                            break;
                        case 2:
                            //线下预约
                            $ConsultOfflineTaskModel = new ConsultOfflineTaskModel();
                            $tempOnline = $ConsultOfflineTaskModel->find($param['message_id']);
                            $tempOnline->is_finish = 1;
                            $tempOnline->result_read_auth = 1;
                            $tempOnline->user_dot = 0;
                            $tempOnline->result_id = $id;
                            $tempOnline->save();
                            $ConsultOfflineModel = new ConsultOfflineModel();
                            $offlineInfo = $ConsultOfflineModel->find($param['message_id']);
                            if ($offlineInfo){
                                $offlineInfo->save([
                                    'user_dot' => 0
                                ]);
                                $consultData = [
                                    'consult_id' => $offlineInfo['consult_id'],
                                    'id' => $offlineInfo['id'],
                                    'type' => 'consultOffline'
                                ];
                            }
                            break;
                        case 3:
                            //线上咨询
                            $ConsultOnlineMessageModel = new ConsultOnlineMessageModel();
                            $tempOnline = $ConsultOnlineMessageModel->find($param['message_id']);
                            $tempOnline->is_finish = 1;
                            $tempOnline->result_read_auth = 1;
                            $tempOnline->user_dot = 0;
                            $tempOnline->save();
                            //在发一条已经做完了的消息
                            $addMessage = [
                                'online_id' => $tempOnline->online_id,
                                'rating_scale_id' => $tempOnline->rating_scale_id,
                                'type' => $tempOnline->type,
                                'content' => $tempOnline->content,
                                'uid' => $param['user_id'],
                                'result_id' => $id,
                                'who' => 1,
                                'is_finish' => 1,
                                'time' => time(),
                                'admin_dot' => 1,
                            ];
                            $ConsultOnlineMessageModel->insert($addMessage);
                            $ConsultOnlineModel = new ConsultOnlineModel();
                            $onlineInfo = $ConsultOnlineModel->find($param['message_id']);
                            if ($onlineInfo){
                                $onlineInfo->save([
                                    'admin_dot' => 1,
                                    'user_dot' => 0
                                ]);
                                $consultData = [
                                    'consult_id' => $onlineInfo['consult_id'],
                                    'id' => $onlineInfo['id'],
                                    'type' => 'consultOnline'
                                ];
                            }
                            break;
                        case 4:
                        default:
                            throw new \Exception('暂无其他来源！');
                    }
                    break;
                default:
                    //有新增、修改。只保留一次报告
                    if (!empty($ret)) {
                        $userArchiveModel->where($where)->update($update);
                    } else {
                        //新增
                        $update['time'] = time();
                        $userArchiveModel->insert($update);
                    }
                    break;
            }
            //更新用户表，档案更新时间,更新档案状态
            $userUpdate = [
                'archive_update_time' => time(),
                'is_normal' => 1,
            ];
            $this->mode->where('id', $param['user_id'])->update($userUpdate);
            $this->mode->commit();
            if (!empty($consultData)){
                //推送socket消息
                $socketServer = new Server();
                $fd = $socketServer->uidGetFd([$consultData['consult_id']]);
                $socketServer->push($fd,json_encode([
                    'type' => $consultData['type'],
                    'content' => [
                        'id' => $consultData['id'],
                        'type' => 1
                    ]
                ]),$websocket);
            }
            return success([], '操作成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 新增自定义的模板信息
     * @return bool|string
     */
    public function addUserArchiveCustomTemplate(): bool|string
    {
        $this->mode->startTrans();
        try {
            $data = $this->request->param();
            $outField = ['is_can_custom'];
            $customModel = new UserArchiveCustomTemplateModel();
            $model = UserArchiveTemplateModel::query()->withoutField($outField)->where('is_can_custom', '=', 1)->find($data['id']);
            if (empty($model))
                return error('没有这个模板');
            $insertArr = $model->toArray();
            $insertArr['user_id'] = $data['user_id'];
            $insertArr['template_id'] = $data['id'];
            unset($insertArr['id']);

            $newId = $customModel->insertGetId($insertArr);
            //递归增加
            $customModel->recurveInsert($newId, $data['id'], $outField, $data['user_id']);
            $this->mode->commit();
            return success();
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


    /**
     * 获取残疾类型
     * @return bool|string
     */
    public function getDisabilityType(): bool|string
    {
        $data = new UserService($this->app);
        $data = $data->getDisabilityType();
        return success($data);
    }

    /**
     * 批量导出普通用户
     * @return bool|string
     */
    public function UserExport(): bool|string
    {
        try {
            $id = $this->request->param('id');
            if (!is_array($id)) throw new \Exception('参数错误！');
            $UserExportService = new UserExportService($this->app);
            $data = $UserExportService->UserExport($id, $this->userData['unit_id']);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 批量导出咨询师
     * @return bool|string
     */
    public function ConsultExport(): bool|string
    {
        try {
            $id = $this->request->param('id');
            if (!is_array($id)) throw new \Exception('参数错误！');
            $UserExportService = new UserExportService($this->app);
            $data = $UserExportService->ConsultExport($id);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 批量导出管理员
     * @return bool|string
     */
    public function AdminExport(): bool|string
    {
        try {
            $id = $this->request->param('id');
            if (!is_array($id)) throw new \Exception('参数错误！');
            $UserExportService = new UserExportService($this->app);
            $data = $UserExportService->AdminExport($id,$this->userData['unit_id']);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 设置部门管理员
     * @return bool|string
     */
    public function SetDepartmentAdmin(): bool|string
    {
        try {
            $uid = $this->request->param('uid');
            $department_id = $this->request->param('department_id');
            $DepartmentAdminModel = new DepartmentAdminModel();
            $DepartmentAdminModel->where('uid', '=', $uid)->update([
                'is_del' => 1,
                'del_time' => time(),
            ]);
            if (!empty($department_id)){
                $data = [];
                foreach ($department_id as $item) {
                    $data[] = [
                        'department_id' => $item,
                        'uid' => $uid,
                        'time' => time()
                    ];
                }
                if (count($data)) {
                    $DepartmentAdminModel->insertAll($data);
                }
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取部门管理员
     * @return bool|string
     */
    public function GetDepartmentAdmin(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $DepartmentAdminModel = new DepartmentAdminModel();
            $department_id = $DepartmentAdminModel->where('uid', '=', $id)->column('department_id');
            return success($department_id);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * word转pdf
     * @return bool|string
     */
    public function getDdf(): bool|string
    {
        try {
            $path = $this->request->param('path');
            WordToPdf($path);
            return success(str_replace('docx', 'pdf', $path));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 咨询统计导出-单个
     * @return bool|string
     */
    public function ConsultationStatisticsExport(): bool|string
    {
        try {
            $param = $this->request->param();
            $upload = new \app\common\Upload();
            // 设置上传类型和文件大小
            $upload = $upload->defaultConfig();
            $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/user_template/ConsultantCount.docx');
            $templateProcessor->setValue('name', $param['name']??' '); // 替换模板中的变量
            $templateProcessor->setValue('sex', $param['sex']??' '); // 替换模板中的变量
            $templateProcessor->setValue('age', $param['age']??' '); // 替换模板中的变量
            $templateProcessor->setValue('unit_name', $param['unit_name']??' '); // 替换模板中的变量
            $templateProcessor->setValue('department_name', $param['department_name']??' '); // 替换模板中的变量
            /*咨询师标签-开始*/
            foreach($param['userTag'] as $key=>$value){
                $index = $key+1;
                $templateProcessor->setImageValue('tag'.$index, ['path' => '.'.$value, 'width' => 60, 'height' => 40]);//标签
            }
            $tempCount = count($param['userTag']);
            if($tempCount<10){
                //默认设置每个值都为空
                for ($i=$tempCount+1;$i<=10;$i++){
                    $templateProcessor->setValue('tag' . $i, ' ');//标签
                }
            }
            //图1
            if (!empty($param['img'])){
                $img = $upload->upload($param['img'],'base64','.png');
                $templateProcessor->setImageValue('img', ['path' => $img, 'width' => 500, 'height' => 400]);
            }else{
                $templateProcessor->setValue('img', ''); // 替换模板中的变量
            }
            //图2-多图
            if (!empty($param['img1'])){
                $templateProcessor->cloneRow('img1', count($param['img1']), true, true);
                foreach($param['img1'] as $key=>$value){
                    $index = $key+1;
                    $img = $upload->upload($value,'base64','.png');
                    $templateProcessor->setImageValue('img1#' . $index, ['path' => $img, 'width' => 500, 'height' => 400]);
                }
            }else{
                $templateProcessor->setValue('img1', ''); // 替换模板中的变量
            }
            //图3
            if (!empty($param['img2'])){
                $img = $upload->upload($param['img2'],'base64','.png');
                $templateProcessor->setImageValue('img2', ['path' => $img, 'width' => 500, 'height' => 400]);
            }else{
                $templateProcessor->setValue('img2', ''); // 替换模板中的变量
            }
            // 保存修改后的文档
            $ext = '.docx';
            $save_name = '/export/consultant_count'.date('Ym').'/'.date('d').'_'.time().uniqid();
            $file_path  = dirname('./public' . $save_name.$ext);
            folder_build($file_path);
            $templateProcessor->saveAs('./public' . $save_name.$ext);
            return success([
                'word' => oss('./public' . $save_name . $ext, $ext)
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 自评记录导出
     * @return bool|string
     */
    public function selfExport(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $userArchiveModel = new UserArchiveModel();
            $info = $userArchiveModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');

            $content = json_decode($info['content'],true);
            $contentData = [];
            foreach ($content as $v){
                $contentData[$v['questionId']] = $v['answersId'];
            }

            $UserArchiveTemplateModel = new UserArchiveTemplateModel();
            $data = $UserArchiveTemplateModel->field('id,name')
                ->where('type_id','=',$info['type_id'])
                ->with([
                    'templateOptions'
                ])->select()->toArray();
            $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/user_template/self.docx');
            $templateProcessor->setValue('update_time', date('Y年m月d日',$info['time'])); // 替换模板中的变量

            $templateProcessor->cloneBlock('list', count($data), true, true);
            foreach ($data as $key=>$value){
                $index = $key + 1;
                $templateProcessor->setValue('title#' . $index, $value['name'] ?? ' ');
                $answer = '';
                foreach ($value['templateOptions'] as $v){
                    if ($contentData[$v['template_id']] == $v['id']){
                        $answer .= $v['name']."     ✓\n";
                    }else{
                        $answer .= $v['name']."\n";
                    }
                }
                $templateProcessor->setValue('answer#' . $index, $answer);
            }
            // 保存修改后的文档
            $ext = '.docx';
            $save_name = './export/self'.date('Ym').'/'.date('d').'_'.time().uniqid();
            $file_path  = dirname($save_name.$ext);
            folder_build($file_path);
            $templateProcessor->saveAs($save_name.$ext);
            return success([
                'url' => oss($save_name.$ext, $ext)
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 自评记录删除
     * @return bool|string
     */
    public function selfDel(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $userArchiveModel = new UserArchiveModel();
            $info = $userArchiveModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info->save([
                'is_del' => 1,
                'del_time' => time()
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

}
